/**
 * 验证手机验证码并创建订单导出接口
 */

import React, { useState, useEffect, useMemo } from "react";
import { Form, Input, Button, Row, Col, message } from "antd";
import { CommonModal } from "@/pages/OrderModule/common/components/CommonModal";
import CommonLoading from "@/components/CommonLoading";
import { getCode, createExportTask, verificationCode } from "@/services/user";
import { getDifferUserDetails } from "@/utils/authority";
import { mobile } from "@/utils/rule";
import { FileExcelOutlined } from "@ant-design/icons";
import ReactDOM from "react-dom/client";
import useDownloadStore from '@/stores/download';
import { find } from "lodash";
import styles from './index.module.less'

const layout = {
	labelCol: {
		span: 8
	},
	wrapperCol: {
		span: 14
	}
};

//处理下载动画逻辑
const documentJumpAnimate = (container, updateStatus) => {
	// 元素
	const startConfig = document.getElementById('download-icon-modal')?.getBoundingClientRect();

	const endConfig = document.getElementById('global-header-download-icon')?.getBoundingClientRect();

	const body = container || document.body;
	const flyRound = document.createElement('div');
	body.appendChild(flyRound);
	ReactDOM.createRoot(flyRound).render(<FileExcelOutlined className={styles.downloadIcon} />);
	body.appendChild(flyRound);

	// 位置信息
	const { top: startTop, left: startLeft } = startConfig;
	const { top: endTop, left: endLeft } = endConfig;

	// 样式
	flyRound.setAttribute('style', `
		transition: all .5s;
		position: fixed;
		top: ${startTop}px;
		left: ${startLeft}px;
		z-index: 2000`);

	const flyTimer = setTimeout(() => {
		flyRound.style.transform = `translate3d(${(endLeft - startLeft - 12)}px, ${(endTop - startTop)}px, 0)`;
		const removeTimer = setTimeout(() => {
			clearTimeout(flyTimer);
			clearTimeout(removeTimer);
			body.removeChild(flyRound);
			updateStatus(true);
		}, 500);
	}, 1);
};

const ExportTelCodeModal = props => {
	const  { item = {}, orderList, selectKeys, handleCancel } = props;

	const { taskType } = item;

	const searchForm = props.searchForm || props.formData;

	const { isBatch } = item;
	const [second, setSecond] = useState(0);
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	const [isOk, setIsOk] = useState(false);
	const [form] = Form.useForm();

	const updateStatus = useDownloadStore((state) => state.updateStatus);

	const snArr = useMemo(() => {
		if(isBatch) {
			const arr = [];
			selectKeys.forEach(item => {
				const obj = find(orderList, ["id", item]);
				arr.push(obj.sn);
			});
			return arr;
		} 
		return []
	}, [selectKeys, orderList]);

	useEffect(() => {
		form.setFieldsValue({
			mobile: getDifferUserDetails()?.mobile,
			code: null
		});
	}, []);

	useEffect(() => {
		setOpen(true);
	}, [])

	//导出任务
	const handleCreateExportTask = async () => {
		setLoading(true);
		const { success, msg = "" } = await createExportTask({
			businessParam: isBatch ? JSON.stringify({ snArr: snArr }) : JSON.stringify(searchForm),
			taskType,
		});
		if (success) {
			message.success(msg);
			setIsOk(true);
			setOpen(false);
		}
		setLoading(false);
	};

	//获取验证码
	const code = async val => {
		const res = await getCode({
			...val,
			type: 9
		});
		if (res.success) {
			message.success("验证码发送成功!");
		}
	};

	//获取验证码点击校验倒数事件
	const verification = async () => {
		form.validateFields(["mobile"]).then(value => {
			let num = 59;
			setSecond(59);
			let seconds = setInterval(() => {
				num = num - 1;
				setSecond(num);
				if (num === 0) {
					clearInterval(seconds);
					setSecond(0);
				}
			}, 1000);
			code(value);
		});
	};

	//取消弹框点击事件
	const ModalCancel = async () => {
		setOpen(false);
	};

	const afterClose = () => {
		if(isOk) {
			documentJumpAnimate(null, updateStatus);
		}
		handleCancel();
	}

	// 验证码提交
	const onOk = () => {
		form
			.validateFields()
			.then(async val => {
				setLoading(true);
				const res = await verificationCode({
					code: val.code,
					phone: val.mobile,
					type: 9
				});
				setLoading(false);
				if (res.success) {
					handleCreateExportTask();
				}
			})
			.catch(() => { });
	};

	return (
		<>
			<CommonModal title={{ title: "安全验证" }} open={open} width="480px" onOk={onOk} onCancel={ModalCancel} afterClose={afterClose}>
				<div style={{ marginBottom: 24, paddingLeft: "5%" }}>为确保数据安全，该操作需二次验证</div>
				<Form {...layout} name="export-tel-code" form={form}>
					<Form.Item
						label="手机号"
						name="mobile"
						rules={[
							{
								required: true,
								message: "请输入正确的手机号!"
							},
							mobile
						]}
					>
						<Input placeholder="请输入手机号" disabled={true} />
					</Form.Item>

					<Form.Item label="手机验证码">
						<Row gutter={8}>
							<Col span={12}>
								<Form.Item
									name="code"
									rules={[
										{
											required: true,
											message: "请输入手机验证码!"
										}
									]}
								>
									<Input placeholder="请输入手机验证码" autoComplete="off" />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Button style={{ width: "109px" }} disabled={second} onClick={verification}>
									{second ? `${second}s` : "获取验证码"}
								</Button>
							</Col>
						</Row>
					</Form.Item>
				</Form>
				<CommonLoading loading={loading} />
			</CommonModal>
			<div id="download-icon-modal" style={{ position: 'fixed', left: '50%', top: '50%' }}></div>
		</>
	);
};

export default ExportTelCodeModal;
